<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口地址" prop="path">
        <el-input v-model="queryParams.path" placeholder="请输入接口地址" clearable style="width: 240px"
          @keyup.enter="getList" />
      </el-form-item>
      <el-form-item label="接口名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入接口名称" clearable style="width: 240px"
          @keyup.enter="getList" />
      </el-form-item>
      <el-form-item label="权限字符串" prop="permissionKey" label-width="80px">
        <el-input v-model="queryParams.permissionKey" placeholder="请输入权限字符串" clearable style="width: 240px"
          @keyup.enter="getList" />
      </el-form-item>
      <el-form-item label="启用状态" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择启用状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleScan" v-hasFunc="'api:perm:sync'">
          <IconPlus name="scan" style="margin-right:5px ;" />接口扫描
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="handleStatus(true)" v-hasFunc="'api:perm:status'"
          :disabled="multiple">一键启用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleStatus(false)" v-hasFunc="'api:perm:status'"
          :disabled="multiple">一键禁用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="toggleLogTrack(true)" v-hasFunc="'api:perm:trackstatus'" icon="Notebook"
          :disabled="multiple">开启日志</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="toggleLogTrack(false)" v-hasFunc="'api:perm:trackstatus'"
          icon="Notebook" :disabled="multiple">关闭日志</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table ref="tableRef" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
      @row-click="handleRowClick">
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="接口地址" align="left" prop="path" :show-overflow-tooltip="true"
        v-if="columns.showColumn('path')">
        <template #default="scope">
          {{ scope.row.path }}
        </template>
      </el-table-column>
      <el-table-column label="接口名称" align="center" prop="name" :show-overflow-tooltip="true"
        v-if="columns.showColumn('name')">
      </el-table-column>
      <el-table-column label="请求方法" align="center" prop="httpMethod" :show-overflow-tooltip="true"
        v-if="columns.showColumn('httpMethod')">
        <template #default="scope">
          {{ scope.row.httpMethod }}
        </template>
      </el-table-column>
      <el-table-column label="接口描述" align="center" prop="desc" :show-overflow-tooltip="true"
        v-if="columns.showColumn('desc')">
        <template #default="scope">
          {{ scope.row.desc }}
        </template>
      </el-table-column>
      <el-table-column label="权限字符串" align="left" prop="permissionKey" :show-overflow-tooltip="true"
        v-if="columns.showColumn('permissionKey')">
        <template #default="scope">
          {{ scope.row.permissionKey }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" :show-overflow-tooltip="true"
        v-if="columns.showColumn('createdAt')">
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" :show-overflow-tooltip="true"
        v-if="columns.showColumn('updatedAt')">
        <template #default="scope">
          {{ parseTime(scope.row.updatedAt) }}
        </template>
      </el-table-column>

      <el-table-column label="启用状态" align="center" prop="isEnabled" :show-overflow-tooltip="true"
        v-if="columns.showColumn('isEnabled')">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.isEnabled" />
        </template>
      </el-table-column>

      <el-table-column label="授权访问" align="center" prop="authRequired" :show-overflow-tooltip="true" width="80">
        <template #default="{ row }">
          <dict-tag :options="sys_yes_no" :value="row.authRequired" />
        </template>
      </el-table-column>

      <el-table-column label="日志记录" align="center" prop="isTrack" :show-overflow-tooltip="true" width="80">
        <template #default="{ row }">
          <dict-tag :options="sys_normal_disable" :value="row.isTrack" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" text icon="edit" @click="handleUpdate(scope.row)"
            v-hasFunc="'api:perm:put'">修改</el-button>
          <!-- <el-button type="primary" text icon="delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']">删除</el-button> -->
          <!-- <el-button type="primary" text icon="view" @click="handleView(scope.row)"
            v-hasPermi="['system:menu:view']">查看</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" draggable align-center>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :lg="24">
            <el-form-item label="接口名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入接口名称" clearable type="textarea" :rows="1" show-word-limit
                resize="none" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="接口地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入接口地址" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="请求方法" prop="httpMethod">
              <el-input v-model="form.httpMethod" placeholder="请输入请求方法" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="授权访问" prop="authRequired">
              <el-radio-group v-model="form.authRequired">
                <el-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="启用状态" prop="isEnabled">
              <el-radio-group v-model="form.isEnabled">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :lg="24" v-show="form.authRequired">
            <el-form-item label="权限字符串" prop="permissionKey">
              <el-input v-model="form.permissionKey" placeholder="请输入权限字符串" clearable />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="日志记录" prop="isTrack">
              <el-radio-group v-model="form.isTrack">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="接口描述" prop="desc">
              <el-input v-model="form.desc" placeholder="请输入接口描述" clearable type="textarea" :rows="6" resize="none" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm" v-if="operateType == 0 || operateType == 1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
    
    <ScanResult v-model="scanState.show" :loading="scanState.loading" :data="scanState.data"
      @onConfirm="onSyncConfirm" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listApiPermissions, getApiPermissions, addApiPermissions, updateApiPermissions, apiSync, apiPermissionsDiff, apiPermissionsSetStatus, apiPermissionsSetTrackStatus } from "@/api/system/apipermissions.js";

import ScanResult from "./ScanResult.vue"

const { proxy } = getCurrentInstance()

//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
//列表ref
const tableRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

// 查询参数
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  name: undefined,
  path: undefined,
  permissionKey: undefined,
  // sort: "createdAt",
});
const { sys_normal_disable, sys_yes_no } = proxy.useDict("sys_normal_disable", "sys_yes_no");

const state = reactive({
  single: true,
  multiple: true,
  form: {

  },
  rules: {
    name: [{ required: true, message: "接口名称不能为空", trigger: "blur" }],
    authRequired: [{ required: true, message: "请选择是否需要授权访问", trigger: "blur" }],
    isEnabled: [{ required: true, message: "请选择启用状态", trigger: "blur" }],
    isTrack: [{ required: true, message: "请选择是否请用日志记录", trigger: "blur" }],
  },
  options: {

  }
})

const { form, rules, single, multiple } = toRefs(state)

const scanState = reactive({
  show: false,
  loading: false,
  data: {
    added: [],
    deleted: [],
  },
})

//所有列
const columns = ref([
  { visible: true, prop: 'path', label: '接口地址' },
  { visible: true, prop: 'name', label: '接口名称' },
  { visible: true, prop: 'httpMethod', label: '请求方法' },
  { visible: true, prop: 'desc', label: '接口描述' },
  { visible: true, prop: 'permissionKey', label: '权限字符串' },
  { visible: true, prop: 'isEnabled', label: '启用状态' },
  { visible: true, prop: 'authRequired', label: '授权访问' },
  { visible: true, prop: 'isTrack', label: '日志记录' },
  { visible: true, prop: 'createdAt', label: '创建时间' },
  { visible: true, prop: 'updatedAt', label: '更新时间' }
]);

// 获取列表方法
const getList = () => {
  loading.value = true;
  listApiPermissions(queryParams).then((response) => {
    dataList.value = response.result;
    total.value = response.totalNum;
    loading.value = false;
  });
};

// 重置表单
const reset = () => {

};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageIndex = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  proxy.resetForm('queryFormRef')
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selected.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/**获取差异接口 */
const handleScan = () => {
  scanState.loading = true;
  scanState.show = true;
  apiPermissionsDiff().then(res => {
    scanState.data = res;
    scanState.loading = false;
  })
}

const handleStatus = (status) => {
  const keys = selected.value;
  let data = {
    ids: keys,
    status: status
  }
  let msg = status ? "确认启用所选接口" : "确认禁用所选接口"
  proxy.$modal.confirm(msg)
    .then(() => apiPermissionsSetStatus(data))
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => { });
}

/**开启，关闭日志记录 */
const toggleLogTrack = (status) => {
  const keys = selected.value;
  let data = {
    ids: keys,
    status: status
  }
  let msg = status ? "确认开启所选接口日志记录" : "确认关闭所选接口日志记录"
  proxy.$modal.confirm(msg)
    .then(() => apiPermissionsSetTrackStatus(data))
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => { });

}

// 修改按钮操作
const handleUpdate = (row) => {
  reset();
  operateType.value = 1;
  const key = row.id || selected.value;
  getApiPermissions(key).then((response) => {
    Object.assign(form.value, response);
    title.value = "修改数据";
    open.value = true;
  });
};



// 提交按钮
const submitForm = () => {
  const validateForm = formRef.value?.validate;
  if (validateForm) {
    validateForm((valid) => {
      if (valid) {
        const apiCall = form.value.id ? updateApiPermissions : addApiPermissions;
        apiCall(form.value).then(() => {
          proxy.$modal.msgSuccess("操作成功");
          open.value = false;
          getList();
        });
      }
    });
  }
};

//取消弹窗
const cancel = () => {
  open.value = false;
  proxy.resetForm("form")
}

const handleRowClick = (row) => {
  tableRef.value.toggleRowSelection(row);
}

const onSyncConfirm = (data, done) => {
  apiSync(data).then(res => {
    proxy.$modal.msgSuccess("同步成功");
  }).then(res => {
    done();
    getList();
  })
}

// 页面加载时调用获取列表方法
onMounted(getList);
</script>
 